% replication_code_table_2.m
% 
% This matlab code replicates table 2 in Miyamoto, W., T.L. Nguyen, and 
% H. Oh (2023), "In Search of Dominant Drivers of the Real Exchange Rate," 
% Review of Economics and Statistics.
%



%% setup
close all; clear all
setup_workspace


%% load VAR estimation result files

jj_case=[814:820] ; % case to run VAR
count=0;

countryname = {'USA','CAN','JPN','GBR','DEU','FRA','ITA'};

% Data from 1974Q1-2016Q4 (172 quarterly series)
% VAR 2 lags imply 170 quarterly series (1974Q3-2016Q4)
% Euro flexible exchange rate: 1974Q3-1998Q4 (86 quarterly series)
% Eurozone: 1999Q1-2016Q4 (84 quarterly series)

raw_obs   = cell(7,1);
shock_raw = cell(7,1);
shock_raw_med = cell(7,1);
corr_mat = cell(7,1);
corr_raw_MBC_mat = cell(7,1);
std_MBC = cell(7,1);
std_raw = cell(7,1);

for jj=jj_case
    
    count=count+1;    
    
    ps_tmp.fpath.cucd=pwd; % current folder
    ps_tmp.file_name=['var_case' num2str(jj)];
    cd([ps.fpath.Case '/' ps_tmp.file_name]);
    load([ps_tmp.file_name '_var_result'])
    load([ps_tmp.file_name '_structural_shock'])
    cd(ps_tmp.fpath.cucd)

    setup_workspace;
    
    % Get size
    n_1 = size(eps,2); % n_1: number of MBC variables
    [~,n_2,n_3] = size(eps{1}); % n_2: length of time series, n_3: number of simulations
    
    shock_raw{count} = zeros(n_1,n_2,n_3);
    shock_raw_med{count} = zeros(n_1,n_2); % median
    for jjj = 1:n_1
        shock_raw{count}(jjj,:,:) = squeeze(eps{jjj}); 
        % 1. dominant output shock
        % 2. dominant consumption shock
        % 3. dominant hours worked shock
        % 4. dominant NXY shock
        % 5. dominant RER shock
        % 6. dominant inflation shock
        % 7. dominant interest rate shock
        % 8. dominant investment shock
        
        shock_raw_med{count}(jjj,:) = median(squeeze(shock_raw{count}(jjj,:,:)),2); % median of MBC shock
    end
    
    % Correlation matrix across MBC shocks
    corr_mat{count} = corrcoef(shock_raw_med{count}');       
end

% take country median of the correlation matrix of dominant shocks
val = median(cat(3,corr_mat{:}),3);

% show the appropriate series
val_disp = val([1 2 3 8],[1 2 3 8]);

% Create correlation matrix table
corrtable = array2table([val_disp],...
    'VariableNames',{'Output','Consumption','Hours Worked','Investment'},...
    'RowName',{'Output','Consumption','Hours Worked','Investment'});


%% display table 2
disp('-------')
disp('Table 2')
disp('-------')
disp('Country median correlations of different dominant shocks')
disp(corrtable)

